import { login, logout } from '@/api/sys'
import md5 from 'md5'
import { setToken, removeToken } from '@/utils/auth'


const user = {
  namespaced: true,
  state: () => ({
    token: ''
  }),
  mutations: {
      SET_TOKEN: (state, token) => {
        state.token = token
      }
  },
  actions: {
    Login({commit}, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({
          username,
          password: md5(password)
        }).then(res => {
          setToken(res.datas.accsess_token)
          commit('SET_TOKEN', res.datas.accsess_token)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    LogOut ({commit}) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}

export default user